package com.springcloud.demo.prac_summary;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhouyang
 * @Description
 * @date 2020/11/27
 */
public class waitAndNotify {

    private static volatile Integer i = 0;

    private static AtomicInteger count = new AtomicInteger(2);

    private static Object lock = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            for (int j = 0; j < 100; j++) {
                try {
                    System.out.println(Thread.currentThread().getName());
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (i) {
                    i++;
                }
            }
            synchronized (lock) {
                if (count.decrementAndGet() == 0) {
                    lock.notify();
                }
            }
        });
        thread1.start();
        Thread thread = new Thread(() -> {
            for (int j = 0; j < 100; j++) {
                try {
                    System.out.println(Thread.currentThread().getName());
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (i) {
                    i++;
                }
            }
            synchronized (lock) {
                if (count.decrementAndGet() == 0) {
                    lock.notify();
                }
            }
        });
        thread.start();
        Thread thread3 = new Thread(() -> {
            try {
                synchronized (lock){
                    lock.wait();
                }
                System.out.println(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread3.start();

    }

}
